package com.ceres.farm.dao;

import com.ceres.farm.pojo.CustFarmlandCrops;
import com.ceres.farm.pojo.CustFarmlandDevice;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
import org.springframework.stereotype.Repository;
import tk.mybatis.mapper.common.Mapper;

import java.util.List;

@Repository
public interface CustFarmlandDeviceMapper extends Mapper<CustFarmlandDevice> {
    /**
     * 根据农田ID查询设备
     * @param id
     * @return
     */
    @Select("SELECT * FROM t_cust_farmland_device WHERE fid =#{id}")
    List<CustFarmlandDevice> selectByFid(Integer id);
    /**
     * 安装设备
     */
    @Insert("INSERT INTO t_cust_farmland_device(`fid`, `cdid`, `mstage`, `dstage`, `longitude`, `latitude`) VALUES (#{fid}, #{cdid}, #{mstage}, #{dstage},#{longitude}, #{latitude})")
    Integer insertDevice(CustFarmlandDevice custFarmlandDevice);
    //修改设备为已安装
    @Update("UPDATE t_customer_device SET `install` = '1' WHERE `id` = #{id}")
    Integer updateDevice(@Param("id")Integer id);
    //根据设备查询农作物
    @Select("SELECT * FROM t_cust_farmland_crops WHERE fid=(SELECT fid from t_cust_farmland_device WHERE cdid=#{device})")
    CustFarmlandCrops findCrops(@Param("device")Integer device);
    //根据设备查询指标
    @Select("SELECT iid FROM t_device_index WHERE did =#{device}")
    Integer findIndexName(@Param("device")Integer device);
    //根据农作物名称、成长阶段、检测指标查询标准范围
    @Select("SELECT opt_range FROM t_crops_index WHERE cid =(SELECT id FROM t_crops WHERE `name`=#{cname} AND stage=#{stage}) AND iid=#{indexName}")
    String finIndex(@Param("cname") String cname, @Param("stage") String stage, @Param("indexName") Integer indexName);
    //根据设备ID查询数据指标
    @Select("SELECT unit FROM t_index  WHERE id=(SELECT iid FROM t_device_index WHERE did =#{did})")
    String findUnit(@Param("did")Integer did);
    //启动设备
    @Update("UPDATE t_cust_farmland_device SET mstage = '1' WHERE `id` = #{device}")
    void updateMstageStart(@Param("device")Integer device);
    //停止设备
    @Update("UPDATE t_cust_farmland_device SET mstage = '0' WHERE `id` = #{device}")
    void updateMstageStop(@Param("device")Integer device);
    //根据设备和运行状态修改
    @Update("UPDATE t_cust_farmland_device SET mstage = #{mstage} WHERE `id` = #{device}")
    Integer updateMstageManual(@Param("device") Integer device,@Param("mstage") Integer mstage);
}
